from numpy import linalg
import numpy as np

class AnalyticProcess:
    RI = {
        1 : 0, 2 : 0, 3 : 0.58,
        4 : 0.90, 5 : 1.12, 6 : 1.24,
        7 : 1.32, 8 : 1.41, 9 : 1.45,
        10 : 1.49 
    }

    def __init__(self, DMatrix):
        self.alt_n = 0
        self.PCMatrix = DMatrix
        self.features = None
        self.alternative_scores = []
        self.alternative_matrix = []

    def check_matrix(self, mat):
        n = mat.shape[0]
        lamd, vec = linalg.eig(mat)
        # # debug
        # print(lamd)
        # print(type(lamd))
        lamd_m = 0
        for i, f in enumerate(lamd):
            if np.imag(f) == 0 and np.real(f) >= lamd_m:
                lamd_m = np.real(f)
                features = vec[:, i]
                pass
        if 0 == lamd_m:
            raise Exception("PCMatrix Error. Not Correct Pair !")
        CI = (lamd_m - n ) / (n - 1)
        RC = CI / AnalyticProcess.RI[n]
        return RC, features.transpose()

    def check_layer(self):
        rc, lamd = self.check_matrix(self.PCMatrix)
        if 0.100 >= rc:
            self.features = np.matrix(lamd)
            # print(self.features)
            return True
        exit(0)

    def input_alt_mat(self, mat):
        rc, lamd = self.check_matrix(mat)
        if 0.1 >= rc:
            self.alternative_matrix.append(np.array(lamd)[0])
            return True
        return False

    def set_alt_mat(self):
        pass

    def analyze(self):
        # # Debug
        # print("analyze : ", type(self.alternative_matrix), self.alternative_matrix)
        self.alternative_matrix = np.matrix(self.alternative_matrix)
        result = np.dot(self.features, self.alternative_matrix)
        self.alternative_scores = result
        # debug
        print("Debug Alt_Scores : ", self.alternative_scores)
        # return self.alternative_scores.index(result[0].max())

def check(pMatrix):
    n = pMatrix.shape[0]
    lamd, _ = linalg.eig(pMatrix)
    lamd = np.array([x for x in lamd if 0 == np.imag(x)])
    CI = (lamd.max() - n ) / (n - 1)
    RC = CI / AnalyticProcess.RI[n]
    return RC <= 0.1000


if __name__ == "__main__":
    pm = np.matrix([
        [1, 2, 3],
        [1/2, 1, 2],
        [1/3, 1/2, 1]
    ])
    ahp = AnalyticProcess(pm)
    ahp.check_layer()
    am1 = np.matrix([
        [1, 1/5, 1/2],
        [5, 1, 5],
        [2, 1/5, 1]
    ])
    am2 = np.matrix([
        [1, 1/5, 1/2],
        [5, 1, 5],
        [2, 1/5, 1]
    ])
    am3 = np.matrix([
        [1, 1/5, 1/2],
        [5, 1, 5],
        [2, 1/5, 1]
    ])
    am4 = np.matrix([
        [1, 1/5, 1/2],
        [5, 1, 5],
        [2, 1/5, 1]
    ])
    am5 = np.matrix([
        [1, 1/5, 1/2],
        [5, 1, 5],
        [2, 1/5, 1]
    ])
    print(ahp.input_alt_mat(am1))
    print(ahp.input_alt_mat(am2))
    print(ahp.input_alt_mat(am3))

    ahp.analyze()